package com.example.uchansz.controller;

import com.example.uchansz.common.CommonResult;
import com.example.uchansz.entity.User;
import com.example.uchansz.service.AddUserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.uchansz.rsp.UserLoginResp;

import java.util.concurrent.TimeUnit;

@Controller
public class UserController {
    @Autowired
    AddUserService adduserservice;
    CommonResult commonresult;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * redis的key的前缀
     */
    private static final String TOKEN_KEY_PREFIX = "login.token.";


    /*是注册啊*/
    @ResponseBody
    public String user() {
        return "register";
    }

    @RequestMapping("/register")
    @ResponseBody
    public String addUserService(User user) {
        adduserservice.add(user);
        return "success";
    }

    //根据用户名从DB查询用户信息
    @RequestMapping("/searchuser")
    @ResponseBody
    public String searchUser(int phone, String token) {
        // 验证token
        if (!checkToken(phone,token)) {
            return "token信息不对";
        }

        adduserservice.searchUser(phone);
        return "success";
    }
    //把请求里的密码加密，因为请求里的密码是明文的；
    //然后把加密的密码和你数据库的密码对比，匹配上就是登陆成功了
    //然后随机生成一个字符串，一般10位
    @RequestMapping("/user/login")
    @ResponseBody
    public CommonResult login(int phone, String password) {
        String loginMsg = adduserservice.login(phone, password);
        String token = getRedisToken(phone);
        if (StringUtils.isBlank(token)) {
            // 生成10个字符串
            token = RandomStringUtils.randomAlphabetic(10);
            // 设置到redis并缓存7天
            setTokenToRedis(phone, token, 7, TimeUnit.DAYS);
        }
        // 登录信息
        UserLoginResp userLoginResp = new UserLoginResp();
        userLoginResp.setToken(token);
        userLoginResp.setLoginMsg(loginMsg);
        return new CommonResult(0, "success", userLoginResp);
    }

    /**
     * 设置token到redis（并保存7天）
     *
     * @param phone
     * @param token
     */
    private void setTokenToRedis(int phone, String token, long time, TimeUnit timeUnit) {
        // 缓存7天
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        String key = TOKEN_KEY_PREFIX + phone;
        operations.set(key, token, time, timeUnit);
    }

    /**
     * 给出redis的key
     *
     * @param phone
     * @return
     */
    private String getRedisToken(int phone) {
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        String key = TOKEN_KEY_PREFIX + phone;
        return operations.get(key);
    }

    /**
     * 校验token
     *
     * @param phone
     * @param token token
     * @return
     */
    private boolean checkToken(int phone, String token) {
        String key = TOKEN_KEY_PREFIX + phone;
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        String tokenStr = operations.get(key);
        if (StringUtils.isBlank(token) || StringUtils.isBlank(tokenStr) || !token.equalsIgnoreCase(tokenStr)) {
            // token失效
            return false;
        }
        return true;
    }



}
